package com.chaike.hsq.service.impl;

import com.chaike.common.ConstPool;
import com.chaike.common.util.StringUC;
import com.chaike.hsq.bean.response.BaseHsqResponse;
import com.chaike.hsq.bean.response.common.UploadResponse;
import com.chaike.hsq.consts.HsqConsts;
import com.chaike.hsq.consts.HsqCommonEnum;
import com.chaike.hsq.exception.HuiShouQianException;
import com.chaike.hsq.service.HuiShouQianService;
import com.chaike.hsq.storage.HsqConfigStorage;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;

import java.io.File;
import java.io.InputStream;
import java.util.Map;

/**
 * 慧收钱 公共 服务.
 *
 * @author Luo
 * @version 1.0
 * @date 2022-01-06 17:11
 */
@Slf4j
public class HsqCommonService {

    private final HuiShouQianService huiShouQianService;

    public HsqCommonService(final HuiShouQianService huiShouQianService) {
        this.huiShouQianService = huiShouQianService;
    }

    /**
     * 影像资料上传.
     *
     * @param inputStream 文件流
     * @param oldName     原文件名
     * @return 上传结果
     * @throws HuiShouQianException 接口异常
     */
    public String upload(final InputStream inputStream, final String oldName) throws HuiShouQianException {
        if (inputStream == null || StringUC.isBlank(oldName)) {
            return ConstPool.EMPTY;
        }
        try {
            HsqConfigStorage hsqConfigStorage = huiShouQianService.getHsqConfigStorage();
            // 文件名后缀
            String ext = oldName.substring(oldName.lastIndexOf('.') + 1);
            // 写入本地临时文件再上传
            File tempFile = File.createTempFile(String.valueOf(System.currentTimeMillis()), ext);
            FileUtils.copyInputStreamToFile(inputStream, tempFile);
            // 请求体参数
            Map<String, Object> params = Maps.newHashMap();
            params.put(HsqConsts.AGENT_MERCHANT_NO, hsqConfigStorage.getAgentMerchantNo());
            params.put(HsqConsts.FILE, tempFile);
            // 发起请求
            BaseHsqResponse response = huiShouQianService.postObject(hsqConfigStorage.getUploadUrl(), params);
            // 上传完成删除临时文件
            if (!tempFile.delete()) {
                log.warn("删除文件失败！");
            }
            // 请求成功
            UploadResponse result = response.toResult(UploadResponse.class);
            // 上传成功
            if (HsqCommonEnum.UploadStatus.SUCCESS.getStatus().equals(result.getStatus())) {
                return result.getFileId();
            }
            throw new HuiShouQianException(response.getErrorMsg());
        } catch (HuiShouQianException e) {
            throw e;
        } catch (Exception e) {
            log.error("上传文件：{}到慧收钱失败：{}", oldName, ExceptionUtils.getStackTrace(e));
        }
        return ConstPool.EMPTY;
    }

}
